package com.qf58.search.model.service.impl;

import com.qf58.search.commons.ESConnect;
import com.qf58.search.commons.IndexConfig;
import com.qf58.search.exception.APIException;
import com.qf58.search.exception.ServiceException;
import com.qf58.search.index.BaseInsert;
import com.qf58.search.index.BaseSearch;
import com.qf58.search.index.BaseUpdate;
import com.qf58.search.model.service.ArticleService;
import com.qf58.search.page.BoolPager;
import com.qf58.search.pub.APICode;
import com.qf58.search.pub.SearchFactor;
import com.qf58.search.utils.URISplitUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.client.transport.TransportClient;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: zhubo
 * Date: 2017-08-30
 * Time: 16:31
 */
@Service("articleService")
public class ArticleServiceImpl implements ArticleService {


    @Override
    public String insertIndex(String jsonStr) throws ServiceException{
        TransportClient client = null;
        try{
            client = ESConnect.getInstance().getTransportClient();
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException(APICode.ES_CONNECT_ERROR);
        }
        try{
            String id = BaseInsert.basicInsert(client, IndexConfig.articleIndex,IndexConfig.articleType,null,jsonStr);
            return id;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException(APICode.ES_INSERT_ERROR);
        }
    }

    /**
     *
     * @param uriStr
     * @return
     * @throws ServiceException
     */
    @Override
    public BoolPager searchIndex(String uriStr)  throws ServiceException {
        try{
            Map<String,String> map = URISplitUtils.splitQuery(uriStr);
            String pageNo = map.get("pageNo");
            String pageSize = map.get("pageSize");
            String labelIds = map.get("labelIds");
            String[] labids = null;
            if(StringUtils.isNotBlank(labelIds)){
                labids = labelIds.split("|");
            }
            String articleCategoryId = map.get("articleCategoryId");
            String sort = map.get("sort");
            BoolPager boolPager = new BoolPager();
            boolPager.setFields(new String[]{"id"});
            boolPager.setPageNo(Integer.parseInt(pageNo));
            boolPager.setPageSize(Integer.parseInt(pageSize));
            if(StringUtils.isNotBlank(labelIds)){
                Map<String,Object[]> shouldMap = new HashMap<String,Object[]>();
                shouldMap.put("labelIds",labids);
                boolPager.setShouldQuery(shouldMap);
            }
            if(StringUtils.isNotBlank(articleCategoryId)){
                Map<String,Object> mustMap = new HashMap<String,Object>();
                mustMap.put("articleCategoryId",articleCategoryId);
                boolPager.setMustQuery(mustMap);
            }

            if(StringUtils.isNotBlank(sort)){
                Map<String,Integer> sortMap = new LinkedHashMap<String,Integer>();
                String[] sortRules = sort.split(",");
                for (String sortRule: sortRules) {
                    String[] sortR = sortRule.split("_");
                    if(sortR.length == 1){
                        sortMap.put(sortR[0], SearchFactor.ASC);
                    }else if(sortR.length == 2){
                        if("desc".equals(StringUtils.lowerCase(sortR[1]))){
                            sortMap.put(sortR[0],SearchFactor.DESC);
                        }else{
                            sortMap.put(sortR[0], SearchFactor.ASC);
                        }
                    }
                }
                boolPager.setSortFields(sortMap);
            }

            TransportClient client  = ESConnect.getInstance().getTransportClient();
            boolPager.set_index(IndexConfig.articleIndex);
            boolPager.set_type(IndexConfig.articleType);
            boolPager = BaseSearch.boolQuery(client,boolPager);

            return boolPager;

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public boolean updateIndex(String jsonStr, Long id) throws ServiceException {
        TransportClient client = null;
        try{
            client = ESConnect.getInstance().getTransportClient();
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException(APICode.ES_CONNECT_ERROR);
        }
        try{
            BaseUpdate.updateById(client,IndexConfig.articleIndex,IndexConfig.articleType,id.toString(),jsonStr);
            return true;
        }catch (Exception e){
            e.toString();
            throw new ServiceException(APICode.ES_UPDATE_ERROR);
        }
    }
}
